#include <bits/stdc++.h>
// 2025/02/04
// tag:
// Author: Zhang Muen
using namespace std;

using int64 = int64_t;

struct Item {
    int w, v;
} Tree[100001];

int n, cnt, W, dp[1001];
bitset<100001> type;

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    char c;
    int h1, h2, m1, m2;
    cin >> h1 >> c >> m1 >> h2 >> c >> m2 >> n;
    W = h2 * 60 + m2 - h1 * 60 - m1;
    for (int i = 1; i <= n; i++) {
        int v, w, m;
        cin >> w >> v >> m;
        if (m == 0){
            Tree[++cnt].v = v, Tree[cnt].w = w, type[cnt] = 1;
            continue;
        }
        for (int j = 1; j <= m; j <<= 1) {
            cnt++;
            Tree[cnt].v = j * v;
            Tree[cnt].w = j * w;
            m -= j;
        }
        if (m) {
            cnt++;
            Tree[cnt].v = m * v;
            Tree[cnt].w = m * w;
        }
    }
    for (int i = 1; i <= cnt; i++)
        if (type[i])
            for (int j = Tree[i].w; j <= W; j++)
                dp[j] = max(dp[j], dp[j - Tree[i].w] + Tree[i].v);
        else
            for (int j = W; j >= Tree[i].w; j--)
                dp[j] = max(dp[j], dp[j - Tree[i].w] + Tree[i].v);
    cout << dp[W] << endl;
    return 0;
}